#!/usr/bin/python

"""
__version__ = "$Revision: 1.33 $"
__date__ = "$Date: 2005/12/13 11:13:22 $"
"""

from PythonCard import dialog, model
import outlook

"""
The Document class below has a reference to the view, so it is responsible for
updating the fields in the view.

There should be an abstract Document class, an abstract RecordsDocument subclass
and finally a DictionaryRecordsDocument or a name that reflects that the actual
records are stored as a list of dictionaries.

If the Document was stored as a DBM or dictionary of dictionaries then an additional
field would be needed to keep track of record order and goPrevRecord, goNextRecord,
goFirstRecord, and goLastRecord would have to be modified to use that ordering.

"""

class Document:
    def __init__(self, view):
        self.view = view
        self.db = db # To expose db in the shell.
        self.fieldNames = self.getFieldNames()
        if db.addressSet.count() > 0:
            self.current = db.addressSet.first()
            self.displayRecord()
        else:
            self.newRecord()

    def close(self):
        transaction.commit()
        db.pack()

    """
    This should probably be a list supplied as part of initialization.
    There might also be a list for field order and fields to search.
    There isn't any meta-data at this point, so there isn't field type
    info either.
    """
    def getFieldNames(self):
        fieldNames = []
        for wName in self.view.components.keys():
            widget = self.view.components[wName]
            wClass = widget.__class__.__name__
            if wClass in ['TextField', 'TextArea'] and widget.visible:
                fieldNames.append(wName)
        if fieldNames.count('Notes') == 0:
            fieldNames.append('Notes')
        return fieldNames

    def displayRecord(self):
        self.clearFields()
        for fieldName in self.fieldNames:
            field = getattr(self.current, fieldName)
            self.view.components[fieldName].text = field()

    def clearFields(self):
        for fieldName in self.fieldNames:
            self.view.components[fieldName].text = ""
        
    def saveRecord(self):
        if db.addressSet.count() == 0:
            return
        for fieldName in self.fieldNames:
            field = getattr(self.current, fieldName)
            field.set(self.view.components[fieldName].text)
        transaction.commit()

    def newRecord(self):
        self.saveRecord()
        self.current = db.Address(Name='Enter Name',
                                  Company='Enter Company')
        self.displayRecord()

    def deleteRecord(self):
        # Should probably do a dialog here to give the user a chance to cancel.
        key = self.current.getKey()
        maxKey = db.addressSet.maxKey()
        db.addressSet.delete(self.current)
        if db.addressSet.count() == 0:
            self.current = db.Address()
        elif key == maxKey:
            self.current = db.addressSet.last()
        else:
            self.current = db.addressSet.next(self.current)
        self.displayRecord()

    def goPrevRecord(self):
        self.saveRecord()
        self.current = db.addressSet.prev(self.current)
        self.displayRecord()

    def goNextRecord(self):
        self.saveRecord()
        self.current = db.addressSet.next(self.current)
        self.displayRecord()

    def goFirstRecord(self):
        self.saveRecord()
        self.current = db.addressSet.first()
        self.displayRecord()

    def goLastRecord(self):
        self.saveRecord()
        self.current = db.addressSet.last()
        self.displayRecord()

    def findRecord(self, searchText, caseSensitive):
        return
##        # we can't search unless there is at least one record
##        if len(self.records) > 1:
##            self.saveRecord(self.current)
##            current = self.current
##            if not caseSensitive:
##                searchText = searchText.lower()
##            while 1:
##                for name in self.fieldNames:
##                    if caseSensitive:
##                        fieldText = self.records[self.current][name]
##                    else:
##                        fieldText = self.records[self.current][name].lower()
##                    offset = fieldText.find(searchText)
##                    if offset != -1:
##                        # if the text is found in the Notes field and it isn't visible
##                        # then the selection below doesn't work without making the field
##                        # visible, but then the Show Notes/Hide Notes button will be out
##                        # of sync if we just set visible = 1
##                        # so some different logic is really needed here
##                        #self.view.components[name].visible = 1
##                        # the solution below is a hack
##                        if not self.view.components[name].visible:
##                            self.view.on_showNotes_command(self.view.components['ShowNotes'], None)
##                        self.view.components[name].setSelection(offset, offset + len(searchText))
##                        self.view.components[name].setFocus()
##                        return
##                self.goNextRecord()
##                if current == self.current:
##                    return
                    

class Addresses(model.Background):

    def on_initialize(self, event):
        if not outlook.WIN32_FOUND:
            self.menuBar.setEnabled('menuFileImportOutlook', 0)
        self.document = Document(view=self)

    def doExit(self):
        self.document.close()

    def on_close(self, event):
        self.doExit()
        event.skip()


    def on_fileImportOutlook_command(self, event):
        addressesToOutlookMap = {'Name':'FullName',
                                 'Company':'CompanyName',
                                 'Street':'MailingAddressStreet',
                                 'City':'MailingAddressCity',
                                 'State':'MailingAddressState',
                                 'Zip':'MailingAddressPostalCode',
                                 'Phone1':'HomeTelephoneNumber',
                                 'Phone2':'BusinessTelephoneNumber',
                                 'Phone3':'MobileTelephoneNumber',
                                 'Phone4':'Email1Address',
                                 'Notes':'Body'
                                 }
        print "attempting to load Outlook"
        # delayed check for Outlook on win32box
        oOutlook = outlook.MSOutlook()
        if not oOutlook.outlookFound:
            # could also display an error message here
            self.menuBar.setEnabled('menuFileImportOutlook', 0)
            return

        print "loading records..."
        oOutlook.loadRecords()
        print "importing into addresses",
        for oRecord in oOutlook.records:
            print '.',
            aRecord = {}
            for field in addressesToOutlookMap.keys():
                """
                if fld == 'Name':
                    names = addressesToOutlookMap[fld]
                     fullName = r[names[0]] + " " + r[names[1]]
                     aRecord['Name'] = fullName.strip()
                else:
                """
                aRecord[field] = oRecord[addressesToOutlookMap[field]]
            db.Address(Name=aRecord['Name'],
                       Company=aRecord['Company'],
                       Street=aRecord['Street'],
                       City=aRecord['City'],
                       State=aRecord['State'],
                       Zip=aRecord['Zip'],
                       Notes=aRecord['Notes'],
                       Phone1=aRecord['Phone1'],
                       Phone2=aRecord['Phone2'],
                       Phone3=aRecord['Phone3'],
                       Phone4=aRecord['Phone4'])
        transaction.commit()
        print '!'
        print "done importing"
        self.document.goFirstRecord() # show that we imported at least one record

    def on_exit_command(self, event):
        self.close()

    def on_goPrev_command(self, event):
        self.document.goPrevRecord()

    def on_goNext_command(self, event):
        self.document.goNextRecord()

    def on_goFirst_command(self, event):
        self.document.goFirstRecord()

    def on_goLast_command(self, event):
        self.document.goLastRecord()

    def on_findRecord_command(self, event):
        result = dialog.findDialog(self)
        if result.accepted:
            self.document.findRecord(result.searchText, result.caseSensitive)

    def on_editUndo_command(self, event):
        widget = self.findFocus()
        if hasattr(widget, 'editable') and widget.canUndo():
            widget.undo()

    def on_editRedo_command(self, event):
        widget = self.findFocus()
        if hasattr(widget, 'editable') and widget.canRedo():
            widget.redo()

    def on_editCut_command(self, event):
        widget = self.findFocus()
        if hasattr(widget, 'editable') and widget.canCut():
            widget.cut()

    def on_editCopy_command(self, event):
        widget = self.findFocus()
        if hasattr(widget, 'editable') and widget.canCopy():
            widget.copy()

    def on_editPaste_command(self, event):
        widget = self.findFocus()
        if hasattr(widget, 'editable') and widget.canPaste():
            widget.paste()

    def on_editClear_command(self, event):
        widget = self.findFocus()
        if hasattr(widget, 'editable'):
            if widget.canCut():
                # delete the current selection,
                # if we can't do a Cut we shouldn't be able to delete either
                # which is why i used the test above
                sel = widget.replaceSelection('')
            else:
                ins = widget.getInsertionPoint()
                try:
                    widget.replace(ins, ins + 1, '')
                except ValueError:
                    pass

    def on_editSelectAll_command(self, event):
        widget = self.findFocus()
        if hasattr(widget, 'editable'):
            widget.setSelection(0, widget.getLastPosition())

    def on_editNewCard_command(self, event):
        self.document.newRecord()

    def on_editDeleteCard_command(self, event):
        self.document.deleteRecord()

    def on_showNotes_command(self, event):
        target = event.target
        if target.label == 'Show Notes':
            self.components.Notes.visible = 1
            target.label = 'Hide Notes'
        else:
            self.components.Notes.visible = 0
            target.label = 'Show Notes'

if __name__ == '__main__':
    from bdoz import transaction
    from schema import Database
    db = Database(filename='Addresses.fs')
    app = model.Application(Addresses)
    app.MainLoop()
